<template>
  <div class='material-view' :class='commonClass'>
    <div class='menu-view'>
      <a-button @click='isModal = true'>添加分组</a-button>
      <a-tabs v-model:activeKey='queryData.groupId' class='tabs-view' tab-position='left' @change="onQueryEvent">
        <a-tab-pane key='' tab='全部分组'></a-tab-pane>
        <a-tab-pane :key='item.id' :tab='item.name' v-for='item in tabsList'></a-tab-pane>
      </a-tabs>
    </div>
    <a-card class='card-group-view' :bordered='false'>
      <template #title>
        <span style='margin-right: 10px'>{{ getGroupTitle(queryData.groupId) }}</span>
        <template v-if='queryData.groupId'>
          <a-button type='link' size='small' @click='onUpdataGroup'>
            <template #icon>
              <form-outlined />
            </template>
            <span>重命名</span>
          </a-button>
          <a-button type='text' danger size='small' @click='onDeleteGroup'>
            <template #icon>
              <delete-outlined />
            </template>
            <span>删除</span>
          </a-button>
        </template>
      </template>
      <template #extra>
        <a-input-search v-model:value="queryData.name" placeholder="请输入文件名称" style="width: 200px;margin-right: 30px" allow-clear @search="onSearch" />
        <a-upload name='file' multiple :action='uploading.url' :accept='uploading.accept' :show-upload-list='false'
                  @change='onUploading' :disabled='uploadLoading'>
          <a-button type='primary' :loading='uploadLoading'>{{uploadLoading ? '上传中...' : '点击上传'}}</a-button>
        </a-upload>
      </template>
      <a-checkbox-group v-model:value='checkboxGroup' class='file-view'>
        <div style='width: 10px;'></div>
        <div class='file-item' v-for='item in fileList' :key='item.id'>
          <FileItem v-model:name='item.name' :is-checkbox='isCheckbox' :disabled="getDisabled(item)" :item='item' @delete='onDelete'></FileItem>
        </div>
      </a-checkbox-group>
      <div style='padding: 0 20px'>
        <a-pagination v-model:current='queryData.pageNo' v-model:pageSize='queryData.pageSize' size='small'
                      :show-total='total => `共 ${total} 条`' :total='queryData.total' show-size-changer show-quick-jumper @change='onPaginationChange'/>
      </div>
    </a-card>
    <a-modal v-model:visible='isModal' title='提示' centered @ok='onGroupEvent' @cancel='onModelCancel'
             :confirm-loading='isLoading'>
      <a-form layout='vertical'>
        <a-form-item label='分组名称' :rules="[{ required: true, message: '请输入分组名称' }]">
          <a-input v-model:value='groupName' placeholder='请输入分组名称' />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import { materialApi } from '@/api/materialApi';
import { materialGroupApi } from '@/api/materialGroupApi';
import FileItem from './components/FileItem';
import { Modal } from 'ant-design-vue';
import { defineComponent, reactive, ref, onBeforeMount, createVNode } from 'vue';
import { FormOutlined, DeleteOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue';

export default defineComponent({
  components: {
    FileItem,
    FormOutlined,
    DeleteOutlined
  },
  props: {  //指定接收的值，必须指定类型
    isCheckbox: Boolean,
    commonClass: String,
    count: Number,
    type: String
  },
  name: 'material',
  setup(props, {emit}) {
    const tabsList = ref([]);
    const fileList = ref([]);

    const checkboxGroup = ref([]);
    let isLoading = ref(false);
    const uploadLoading = ref(false);
    let isModal = ref(false);
    const groupName = ref('');
    const queryData = reactive({
      name: '',
      groupId: '',
      pageNo: 1,
      pageSize: 10,
      total: 0
    });

    const uploading = reactive({
      url: `${process.env.VUE_APP_API_BASE_URL}/business/admin/upload/uploadFile`,
      accept: '.jpg,.png,.jpeg,.mp4,.mp3'
    });
    onBeforeMount(() => {
      getFindList();
      getFindPage();
    });
    function onSearch () {
      queryData.pageNo = 1
      queryData.pageSize = 10
      getFindPage()
    }
    function onPaginationChange (page, pageSize) {
      queryData.pageNo = page
      queryData.pageSize = pageSize
      getFindPage()
    }
    async function getFindPage() {
      const res = await materialApi.findPage(queryData);
      fileList.value = res.rows;
      queryData.total = res.totalRows
    }

    async function getFindList() {
      const res = await materialGroupApi.findList();
      tabsList.value = res;
    }

    function getGroupTitle(groupId) {
      const list = tabsList.value;
      if (!list.length || !groupId) return '全部分组';
      return list.find(item => item.id == groupId).name;
    }

    function getDisabled(item) {
      const checkboxList = checkboxGroup.value
      if (checkboxList.length >= props.count) return !checkboxList.some(id => id == item.id)
      if (props.type && props.type != item.type) return true
      return false
    }

    return {
      props,
      tabsList,
      fileList,
      uploading,
      uploadLoading,
      isModal,
      checkboxGroup,
      groupName,
      queryData,
      onSearch,
      getFindList,
      getGroupTitle,
      getDisabled,
      onPaginationChange,
      onGroupEvent: async function() {
        isLoading.value = true;
        const groupId = queryData.groupId || '';
        const request = groupId ? materialGroupApi.edit : materialGroupApi.add;
        await request({
          id: groupId,
          name: groupName.value
        }).finally(() => (isLoading.value = false, isModal.value = false));
        Modal.success({ title: '提示', content: '操作成功!' });
        getFindList();
      },
      onSelect: function() {
        const list = fileList.value
        const select = checkboxGroup.value.map(item => list.find(entity => item == entity.id))
        const arrList = select.map(item => item.url)
        emit('change', arrList)
        return arrList
      },
      onQueryEvent: function() {
        queryData.pageNo = 1
        getFindPage()
      },
      onSubmit: function() {
        console.log(this.checkboxGroup.value.join(','));
      },
      onDelete: function(event) {
        const index = fileList.value.findIndex(item => item.id == event.id);
        fileList.value.splice(index, 1);
      },
      onUpdataGroup: function() {
        const name = getGroupTitle(queryData.groupId);
        groupName.value = name;
        isModal.value = true;
      },
      onDeleteGroup: function() {
        Modal.confirm({
          title: '提醒',
          icon: createVNode(ExclamationCircleOutlined),
          content: '确定删除吗?',
          okText: '确定',
          okType: 'danger',
          cancelText: '取消',
          onOk: async () => {
            await materialGroupApi.del({ id: queryData.groupId });
            queryData.groupId = '';
            queryData.pageNo = 1;
            getFindList();
            getFindPage();
          }
        });
      },
      onUploading: async function(event) {
        uploadLoading.value = true
        const file = event.file;
        const res = file.response;
        console.log('file------------', file.type);
        const [type] = file.type.split('/');
        const typeList = ['image', 'video', 'audio'];
        const index = typeList.findIndex(item => item == type);
        if (res && res.code == '00000') {
          await materialApi.add({
            groupId: queryData.groupId,
            type: index + 1,
            name: file.name,
            url: res.data
          });
          queryData.pageNo = 1;
          getFindPage();
          uploadLoading.value = false
        }
      },
      onModelCancel: function() {
        groupName.value = '';
        isModal.value = false;
      }
    };
  }
});
</script>

<style scoped lang='less'>
.material-view {
  width: calc(100% - 60px);
  margin: 30px auto;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: flex-start;
}

.card-group-view {
  width: calc(100% - 120px);
  box-shadow: 0px 2px 10px 0px rgba(103, 103, 103, 0.1);
  border-radius: 8px;
  /deep/.ant-card-body{
    padding: 20px 0;
    padding-right: 10px;
  }
}

.menu-view {
  width: 110px;
  padding-top: 20px;
  padding-bottom: 20px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: white;
  border-radius: 8px;

  .tabs-view {
    width: 100%;
    margin-top: 30px;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: flex-end;

  }
}

.file-view {
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  align-items: flex-start;
  flex-wrap: wrap;
  margin-bottom: 30px;
}

.file-item {
  width: calc(100% / 6 - 10px);
  min-width: 200px;
  margin-bottom: 10px;
}

.file-item + .file-item {
  margin-left: 10px;
}
</style>
